// ==UserScript==
// @name        邮箱下载联系人
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Extract data and download as CSV
// @author       Your Name
// @match        https://exmail.qq.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 数据提取和 CSV 生成的函数
    function generateCSV() {
    // 提取 node_alias
    let aliases = [];
    let nodes = document.evaluate('//*[@id="biz"]//li[@class="tree_node "]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (let i = 0; i < nodes.snapshotLength; i++) {
        let node = nodes.snapshotItem(i);
        aliases.push(node.getAttribute('node_alias'));
    }


    console.log(aliases)
    // 提取 node_txt
    let texts = [];
    let textNodes = document.evaluate('//*[@id="biz"]//li[@class="tree_node "]/div/span[@class="node_txt"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (let i = 0; i < textNodes.snapshotLength; i++) {
        let textNode = textNodes.snapshotItem(i);
        texts.push(textNode.textContent.trim());
    }
    console.log(texts)
    // 合并 aliases 和 texts
    let combinedData = [];
    for (let i = 0; i < Math.min(aliases.length, texts.length); i++) {
        combinedData.push([aliases[i], texts[i]]);
    }

    // 转换为 CSV 格式
    let csvContent = "Node Alias,Node Text\n";
    combinedData.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
    });


    // 创建 Blob
    let blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    let url = URL.createObjectURL(blob);

    return url;
    }

    // 创建触发按钮
    let triggerButton = document.createElement("button");
    triggerButton.textContent = "生成 CSV";

    // 设置按钮样式
    // ...
    triggerButton.style.position = "fixed";
    triggerButton.style.right = "10px";
    triggerButton.style.top = "10px";
    triggerButton.style.padding = "10px";
    triggerButton.style.backgroundColor = "red";
    triggerButton.style.color = "white";
    triggerButton.style.fontSize = "16px";
    triggerButton.style.border = "none";
    triggerButton.style.cursor = "pointer";
    triggerButton.style.zIndex = "1000"; // 确保按钮在最前面

    // 将按钮添加到页面
    document.body.appendChild(triggerButton);

    // 绑定点击事件
    triggerButton.addEventListener('click', function() {
        let csvUrl = generateCSV();
        // 您可以在这里使用 csvUrl
        // 例如，打开新标签下载 CSV 文件
        window.open(csvUrl, '_blank');
    });
})();
